package com.qingke.example;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private final String driver="com.mysql.jdbc.Driver";
	private final String url="jdbc:mysql://localhost:3306/web?useSSL=false";
	private final String u="root";
	private final String p="6775";

	private Connection conn = null;
	private String sql;
	private PreparedStatement ps = null;
	private ResultSet rs = null;
       
    public RegisterServlet() {
        super();
    }

	public void init(ServletConfig config) throws ServletException {
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, u, p);
			System.out.println("Connect to database successfully!");
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		String name=request.getParameter("nickname");
		
		boolean isSuccess=register(username,password,name);
		if(isSuccess){
			response.getWriter().println("<script>alert('register success!');window.location.href='Login.html';</script>");
		}else{
			response.getWriter().append("<script>alert('register failed!');window.history.back(-1);</script>");
			
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	public  boolean isUsernameExists(String username){
		sql="select 'Y' from user where username=?";
		
		try {
			ps=conn.prepareStatement(sql);
			ps.setString(1,username);
			rs=ps.executeQuery();
			if(rs.next()){
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public boolean register(String username,String password,String name){
		if(isUsernameExists(username)){
			return false;
		}
		sql="insert into user(username,password,name) values(?,?,?)";
		
		try {
			ps=conn.prepareStatement(sql);
			ps.setString(1, username);
			ps.setString(2, password);
			ps.setString(3, name);
			int isTrue =ps.executeUpdate();
			if(isTrue>0){
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

}
